package com.shiro.receiver.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.shiro.receiver.entity.Payload;
import com.shiro.receiver.framework.constant.BotEventType;
import com.shiro.receiver.framework.constant.BotOperationType;
import com.shiro.receiver.handler.AbstractEventHandler;
import com.shiro.receiver.handler.EventHandlerStorage;

import java.util.List;

@Slf4j
@Service
public class CallbackManager {

    @Async
    public void handleCallbackAsync(Payload<JSONObject> payload) {
        BotOperationType operationType = BotOperationType.getOperationTypeByValue(payload.getOperationType());
        BotEventType eventType = BotEventType.getEventTypeByValue(payload.getEventType());
        List<AbstractEventHandler> eventHandlerList = EventHandlerStorage.getEventHandlerList(operationType, eventType);
        if (CollUtil.isEmpty(eventHandlerList)) {
            return;
        }
        for (AbstractEventHandler eventHandler : eventHandlerList) {
            try {
                if (!eventHandler.canHandle(payload)) {
                    continue;
                }
                eventHandler.preHandle(payload);
                eventHandler.handle(payload);
                eventHandler.postHandle(payload);
            } catch (Exception e) {
                log.error("[事件处理器执行异常] [EventHandler:{}] [Payload:{}] [异常信息:{}] [异常堆栈:{}]", eventHandler.getClass().getSimpleName(), JSONObject.toJSONString(payload), e.getMessage(), ExceptionUtil.stacktraceToString(e, 500));
            }
        }
    }

}
